<template>
  <div class="tenantMenu_main main_container">
    <div class="main_header">
      <div class="padding_container">
        <div class="left"><Breadcrumb /></div>
        <div class="right">
          <HeaderOperation :parent="this" />
        </div>
      </div>
    </div>
    <div v-loading="loading" class="main_main">
      <SearchBar :parent="this" />
      <div ref="table_container" class="table_container">
        <el-table
          ref="table"
          :data="tableData"
          stripe
          border
          :height="tableHeight"
          row-key="id"
          :cell-style="cellStyle"
          @cell-click="cellClick"
          @sort-change="(column)=>{sortChange(column, this)}"
          @selection-change="(val)=>{selectionChange(val, this)}"
        >
          <el-table-column type="selection" width="70" align="center" />
          <Column v-for="(column,index) in tableColumns" :key="index" :prop="column.prop" :is-show="column.isShow" :label="column.label" :sortable="column.sortable" :width="column.width" />

          <el-table-column label="操作" align="center" fixed="right" width="180">
            <template slot-scope="scope">
              <el-button
                v-if="scope.row.status =='0'"
                type="text"
                @click.stop="edit(scope.row)"
              >编辑</el-button>
              <button v-else class="el-button--text button_grey">编辑</button>
              <el-button
                v-if="scope.row.status =='0'"
                type="text"
                @click.stop="deleteOne(scope.row)"
              >删除</el-button>
              <button v-else class="el-button--text button_grey">删除</button>
              <el-button
                v-if="scope.row.status =='1'"
                type="text"
                @click.stop="reviseEdition(scope.row)"
              >升版</el-button>
              <button v-else class="el-button--text button_grey">升版</button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>
    <div class="main_bottom">
      <pagination
        :total="total"
        :page.sync="pageData.pageNum"
        :limit.sync="pageData.pageSize"
        :selected-num="selectionsAll.length"
        @pagination="getList"
      />
    </div>
    <el-dialog
      title="BOM导入"
      :visible.sync="dialogVisible"
      width="500px"
    >
      <i class="el-icon-warning-outline" />
      <span class="bom_marter_box">物料编码{{ materialCode }}的BOM已存在，是否替换？</span>
      <div slot="footer" class="dialog-footer">
        <el-checkbox v-model="noAsk">不再询问</el-checkbox>
        <div>
          <el-button type="cancel" @click="noReplaceBOM">不替换</el-button>
          <el-button @click="replaceBOM">替换</el-button>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { list, remove, importMethod, importConfirmV1, importConfirmV2, listAllTreeForImport } from '@/api/engineeringManage/BOMManage'
import { list as materialTypeList } from '@/api/warehouseManagement/materialType'
import AddOrUpdate from './addOrUpdate'
import { getInfo } from '@/api/engineeringManage/BOMManage'
import ShowDetail from '@/components/JLINK2/common/ShowDetailTitle.vue'

export default {
  name: 'Index',
  data() {
    return {
      loading: false,
      pageId: 'BOM管理', // 页面唯一标识
      pageExportId: 'BOM管理导出',
      pageData: {
        pageNum: 1,
        pageSize: 20,
        orderByColumn: 'updateTime',
        isAsc: 'desc'
      },

      dialogVisible: false,
      noAsk: false,
      materialCode: '',
      materialData: {},
      total: 1, // 数据一共有多少条
      mainId: 'id', // 表格行ID
      tableHeight: '0', // 表格高度
      tableData: [], // 表格数据
      tableColumns: [], // 表格实际用的字段
      searchColumns: [], // 搜索区实际用的字段
      selections: [], // 表格当前页所选中的行
      selectionsAll: [], // 表格所有页选中的行
      defaultTableColumns: [// 表格常规字段（初始值）
        { prop: 'statusName', label: '状态', width: '80', canOrder: false },
        { prop: 'code', label: 'BOM编码' },
        { prop: 'materialCode', label: '物料编码' },
        { prop: 'materialName', label: '物料名称', canOrder: false },
        { prop: 'materialModel', label: '规格型号', canOrder: false },
        { prop: 'materialTypeName', label: '物料分类', canOrder: false },
        { prop: 'materialUnitLabel', label: '物料单位', canOrder: false },
        { prop: 'versionCode', label: '版本号', canOrder: false },
        { prop: 'remark', label: '备注', canOrder: false }
      ],
      exportTableColumns: [// 表格常规字段（初始值）
        { prop: 'bomCode', label: 'BOM编码' },
        { prop: 'materialCode', label: '物料编码' },
        { prop: 'materialName', label: '物料名称' },
        { prop: 'materialModel', label: '规格型号' },
        { prop: 'materialTypeName', label: '物料分类' },
        { prop: 'materialUnitLabel', label: '物料单位' },
        { prop: 'bomVersionCode', label: '版本号' },
        { prop: 'needNumber', label: '需求数量' }
      ],
      defaultExport: [
        { prop: 'id', label: '父级编号' },
        { prop: 'parentId', label: '所属父级' }
      ],
      defaultSearchColumns: [// 搜索区常规字段（初始值）
        { prop: 'code', label: 'BOM编码', type: 'input' },
        { prop: 'materialCode', label: '物料编码', type: 'input' },
        { prop: 'materialName', label: '物料名称', type: 'input', canOrder: false },
        { prop: 'materialModel', label: '规格型号', type: 'input', canOrder: false },
        { prop: 'materialUnitLabel', label: '物料单位', type: 'input', canOrder: false },
        { prop: 'versionCode', label: '版本号', type: 'input', canOrder: false },
        { prop: 'status', label: '状态', type: 'select', optionsName: 'statusOptions', canOrder: false },
        { prop: 'materialTypeId', label: '物料分类', canOrder: false, type: 'select', optionsName: 'materialTypeOptions' }
      ],
      operationData: [ // 右上角的操作按钮
        // { label: '新增', perm: 'engineering:bom:add' },
        // { label: '导入', perm: 'engineering:bom:import' },
        // { label: '批量删除', perm: 'engineering:bom:delete' },
        // { label: '批量导出3', perm: 'engineering:bom:export' },
        // { label: '页面配置', perm: '' }
        { label: '新增', perm: '' },
        { label: '导入', perm: '' },
        { label: '批量删除', perm: '' },
        { label: '页面配置', perm: '' }
      ],
      statusOptions: [
        { value: undefined, label: '全部' },
        { value: '1', label: '已提交' },
        { value: '0', label: '草稿' }
      ],
      materialTypeOptions: [],
      showKey: {
        type: 'column_two',
        name: '基本信息',
        keys: [
          { type: 'form', name: 'BOM编码', key: 'code' }, // type: 'form' 表示是普通的表单展示
          { type: 'form', name: '物料编码', key: 'materialCode' },
          { type: 'form', name: '物料名称', key: 'materialName' },
          { type: 'form', name: '规格型号', key: 'materialModel' },
          { type: 'form', name: '物料分类', key: 'materialTypeName' }, // length:'double' 表示占两列
          { type: 'form', name: '物料单位', key: 'materialUnitLabel' },
          { type: 'form', name: '版本号', key: 'versionCode' },
          { type: 'file', name: '附件', fileName: 'fileName', fileRealName: 'fileRealName', fileUrl: 'fileUrl' },
          { type: 'form', name: '备注', key: 'remark', length: 'double' },
          {
            type: 'table', name: '子级物料', key: 'data', columns: [ // type: 'table' 表示是表格// type: 'form' 表示是普通的表单展示
              { type: 'column', name: '物料编码', key: 'materialCode', minWidth: '120' }, // type: 'form' 表示是普通的表单展示
              { type: 'column', name: '物料名称', key: 'materialName', minWidth: '100' },
              { type: 'column', name: '规格型号', key: 'materialModel', minWidth: '100' },
              { type: 'column', name: '物料单位', key: 'materialUnitLabel', minWidth: '100' },
              { type: 'column', name: '需求数量', key: 'needNumber', minWidth: this.SETTINGS.settings_decimalDigits_length, fixed: 'right' },

              { type: 'column', name: '替代料', key: 'replaceMaterialCodeNames', minWidth: '100' },
              { type: 'column', name: '备注', key: 'remark', minWidth: '100' }
            ]
          }
        ]
      }
    }
  },
  mounted() {
    this.getMaterialType()
  },
  methods: {
    getExportData(data) {
      return listAllTreeForImport(data)
    },
    noReplaceBOM() {
      importConfirmV1({
        key: this.materialData.key,
        confirm: this.noAsk ? '1' : ''
      }).then(res => {
        if (res.data.key == 'ok' && res.code == 200) {
          this.dialogVisible = false
          this.$message.success('操作成功')
          this.getList()
          this.noAsk = false
        } else {
          this.dialogVisible = false
          this.$nextTick(() => {
            this.dialogVisible = true
            this.materialCode = res.data.materialCode
            this.materialData = res.data
            this.$message.success('操作成功')
            // this.noReplaceBOM()
          })
        }
      })
    },
    replaceBOM() {
      importConfirmV2({
        key: this.materialData.key,
        confirm: this.noAsk ? '1' : ''
      }).then(res => {
        if (res.data.key == 'ok' && res.code == 200) {
          this.dialogVisible = false
          this.$message.success('操作成功')
          this.getList()
          this.noAsk = false
        } else {
          this.dialogVisible = false
          this.$nextTick(() => {
            this.dialogVisible = true
            this.materialCode = res.data.materialCode
            this.materialData = res.data
            this.$message.success('操作成功')
            // this.noReplaceBOM()
          })
        }
      })
    },
    cellStyle({ row, column }) {
      if (column.property == 'code') {
        return {
          cursor: 'pointer',
          color: '#387bfc'
        }
      }
    },
    cellClick(row, column, cell) {
      switch (column.property) {
        case 'code':
          this.showDetail(row)
          break
      }
    },
    getList() {
      list(this.pageData).then(res => {
        res.data.forEach(item => {
          if (item.status == 1) {
            item.canNotSelectDelete = true
          }
        })
        this.tableData = res.data
        this.total = res.total
        this.$nextTick(() => {
          this.setSelectRow(this)// 设置行选中
          this.tableHeight = this.$refs.table_container.offsetHeight
        })
      })
    },
    getMaterialType() {
      materialTypeList().then(res => {
        res.data.forEach(item => {
          item['value'] = item.id
          item['label'] = item.name
        })
        this.materialTypeOptions = res.data
      })
    },
    refresh() {
      this.pageData.pageNum = 1
      this.getList()
    },
    add() {
      this.$layer.iframe({// 弹框
        content: {
          content: AddOrUpdate, // 传递的组件对象
          parent: this, // 当前的vue对象
          data: {
            tag: 'add'
          }// props
        },
        area: ['1320px', '850px'],
        title: '新增BOM', // 标题
        shadeClose: false // 点击遮罩是否关闭
      })
    },
    edit(row) {
      this.$layer.iframe({// 弹框
        content: {
          content: AddOrUpdate, // 传递的组件对象
          parent: this, // 当前的vue对象
          data: {
            tag: 'edit',
            tagId: row[this.mainId]
          }// props
        },
        area: ['1320px', '850px'],
        title: '编辑BOM', // 标题
        shadeClose: false // 点击遮罩是否关闭
      })
    },
    deleteOne(row) {
      const _this = this
      this.$confirm('确定要删除吗', '删除确认', {
        confirmButtonText: '确定',
        cancelButtonText: '取消', cancelButtonClass: 'cancelConfirm',
        type: 'warning'
      }).then(function() {
        remove(row[_this.mainId]).then(res => {
          _this.$message({
            message: res.msg,
            type: 'success'
          })
          _this.getList()
        })
      }).catch(() => {})
    },
    // 当前页的删除接口
    deleteMethod(deleteIds) {
      return remove(deleteIds)
    },
    showDetail(row) {
      getInfo(row[this.mainId]).then(res => {
        this.$layer.iframe({// 弹框
          content: {
            content: ShowDetail, // 传递的组件对象
            parent: this, // 当前的vue对象
            data: {
              showData: res.data,
              showKey: this.showKey
            }// props
          },
          area: ['1320px', '700px'],
          title: '查看BOM', // 标题
          shadeClose: false // 点击遮罩是否关闭
        })
      })
    },
    reviseEdition(row) {
      this.$layer.iframe({// 弹框
        content: {
          content: AddOrUpdate, // 传递的组件对象
          parent: this, // 当前的vue对象
          data: {
            tag: 'reviseEdition',
            tagId: row[this.mainId]
          }// props
        },
        area: ['1320px', '850px'],
        title: 'BOM升版', // 标题
        shadeClose: false // 点击遮罩是否关闭
      })
    },
    changeBom(row) {
      this.$layer.iframe({// 弹框
        content: {
          content: AddOrUpdate, // 传递的组件对象
          parent: this, // 当前的vue对象
          data: {
            tag: 'change',
            tagId: row[this.mainId]
          }// props
        },
        area: ['1320px', '850px'],
        title: '变更BOM', // 标题
        shadeClose: false // 点击遮罩是否关闭
      })
    },
    importMethod(files) { // 导入接口
      importMethod(files).then(res => {
        this.$message({
          message: res.msg,
          type: 'success'
        })
        this.getList()
      })
    }
  }
}
</script>

<style lang="less" scoped>
.dialog-footer{
  display: flex;
  align-items: center;
  justify-content: space-between;
}
/deep/ .el-dialog__header{
background-color: #387bfc;
display: flex;
justify-content: space-between;
align-items: center;
padding: 10px 20px;
.el-dialog__headerbtn{
  position: unset !important;
}
.el-dialog__title{
  color: white;
  font-size: 15px;
}
.el-dialog__close{
  color: white !important;
}
}
.el-icon-warning-outline{
  font-size: 26px;
    color: rgb(255,153,0);
}
.bom_marter_box{
  font-size: 16px;
}
</style>
